<template>
  <el-upload
    class="avatar-uploader"
    action=""
    :show-file-list="false"
    :http-request="uploadFile"
  >
    <img v-if="value" :src="value" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>

</template>

<script>
import COS from 'cos-js-sdk-v5'
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
    }
  },
  methods: {
    // 上传之前检查是否合格
    beforeUpload(file) {
      const typeList = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp']
      if (typeList.includes(file.type)) {
        this.$message.warning('请上传图片类型文件')
        return false
      }
      const maxSize = 5 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.warning('请上传小于5mb文件')
        return false
      }
    },
    // 上传方法
    uploadFile(params) {
      console.log(params.file)
      // 要上传到腾讯云
      const cosObj = new COS({
        SecretId: 'AKIDYyBC1c1CD1by97rNfmgMo5A1f7SmxwkL',
        SecretKey: 'ReeV9a1MVTEnFaicMuHRTN4YpfLo461k'
      })
      cosObj.putObject({
        Bucket: 'leslie-hm6-1334765491', // 存储桶名称
        Region: 'ap-beijing', // 存储桶地域
        Key: params.file.name, // 文件名称
        StorageClass: 'STANDARD', // 默认模式
        Body: params.file // 文件对象
      }, (err, data) => {
        if (!err) {
          this.$message.success('上传成功')
          this.$emit('input', `https://${data.Location}`)
          console.log(data)
        }
      })
    }
  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
